import { Del } from '@nutui/icons-react-taro'
import { Button, Tabs } from '@nutui/nutui-react-taro'
import { Image, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { autorun, toJS } from 'mobx'
import { useEffect, useState } from 'react'
import LogisticsPopup from './LogisticsPopup/LogisticsPopup';
import { logisticsStore } from './LogisticsPopup/logisticsStore'
import MyEmpty from 'src/components/MyEmpty/MyEmpty'
import MyScrollView from 'src/components/MyScrollView/MyScrollView'
import PageLayer from 'src/components/PageLayer/PageLayer'
import utils from 'src/utils/utils'
import utilsStore from 'src/utils/utilsStore'
import { OrderData, OrderState } from 'types/type'
import myOrderDetailStore from '../MyOrderDetail/myOrderDetailStore'
import styles from './myOrder.module.less'
import myOrderStore from './myOrderStore'
import myOrderApi from './myOrderApi'
import { filter } from 'lodash'

//订单状态
const statusMap: Array<{
    text: string;
    value: OrderState;
    color: string;
}> = [
        { text: "全部", value: "", color: '#808080' },
        { text: "待支付", value: "WAIT_PAY", color: '#FF6B6B' },
        { text: "待发货", value: "WAIT_DELIVERY", color: '#FFA500' },
        { text: "已发货", value: "DELIVERED", color: '#1E90FF' },
        { text: "已收货", value: "RECEIVED", color: '#32CD32' },
        { text: "已关闭", value: "CLOSED", color: '#808080' },
    ];

export default function MyOrder() {

    const [activeTab, setActiveTab] = useState(0);
    const [list, setList] = useState<Array<OrderData>>(toJS(myOrderStore.list));

    useEffect(() => autorun(() => {
        const { orderState } = myOrderStore;
        const index = statusMap.findIndex(s => s.value === orderState);
        setActiveTab(index);
        setList(toJS(myOrderStore.list));
    }, { delay: 30 }), []);

    useEffect(() => {
        const { orderState } = Taro.getCurrentInstance().router?.params || {};
        myOrderStore.setOrderState(orderState as OrderState);
    }, []);

    return (
        <PageLayer
            showBack
            title='我的订单'
            hasHeader
            hasTabBar={false}
        >

            <LogisticsPopup />

            <Tabs
                value={activeTab}
                className={styles.status_bar}
                onChange={(index: number) => {
                    myOrderStore.setOrderState(statusMap[index].value);
                }}
                style={{
                    left: 0,
                    top: utilsStore.titleTop
                }}
            >
                {statusMap.map((s) => (
                    <Tabs.TabPane
                        key={s.value}
                        title={s.text}
                    />
                ))}
            </Tabs>

            {/* 订单列表 */}
            {
                list.length == 0 &&
                <MyEmpty
                    style={{
                        marginTop: "16vh"
                    }}
                    description="暂无订单"
                    actions={[
                        {
                            text: '去逛逛',
                            onClick: () => {
                                Taro.switchTab({
                                    url: '/pages/Category/Category'
                                })
                            }
                        }
                    ]}
                />
            }
            {
                list.length > 0 &&
                <MyScrollView
                    className={styles.goodsList}
                    onScrollBottom={() => {
                        myOrderStore.getNextPage()
                    }}
                    style={{
                        marginTop: utils.rpx2px(90),
                        height: utilsStore.containerHeight,
                    }}
                >
                    {
                        list.map((order: OrderData, i: number) => {
                            return (
                                <View key={order.id} className={styles.order_item}>
                                    <View className={styles.header}>
                                        <Text
                                            className={styles.order_no}
                                            onClick={() => {
                                                myOrderDetailStore.setOrderDetail(order);
                                                // 跳转到订单详情页
                                                Taro.navigateTo({
                                                    url: `/subPages/MyOrderDetail/MyOrderDetail`
                                                })
                                            }}
                                        >订单号: {order.orderCodeMain}
                                        </Text>
                                        {
                                            order.orderState === 'WAIT_PAY' ?
                                                <Button
                                                    type="primary"
                                                    className={styles.pay_btn}
                                                    onClick={() => myOrderStore.payOrder(order.orderCodeMain)}
                                                >支付</Button>
                                                :
                                                <Text
                                                    className={styles.status}
                                                    style={{ color: statusMap.find(s => s.value === order.orderState)!.color }}
                                                >
                                                    {statusMap.find(s => s.value === order.orderState)!.text}
                                                </Text>
                                        }
                                    </View>

                                    {order.childrenList.map((goods) => (
                                        <View key={goods.id} className={styles.goods_item}>
                                            <Image
                                                src={utils.ossSuffix(goods.productDesign.thumbs[0], utils.rpx2px(320))}
                                                className={styles.cover}
                                                onClick={() => {
                                                    Taro.previewImage({
                                                        urls: filter(goods.productDesign.thumbs).map((item) => utils.ossSuffix(item, 1024))
                                                    })
                                                }}
                                                mode="aspectFill" />
                                            {
                                                goods.productDesign.thumbs[1] &&
                                                <Image
                                                    src={utils.ossSuffix(goods.productDesign.thumbs[1], utils.rpx2px(80))}
                                                    className={styles.preImg}
                                                    mode="aspectFill" />
                                            }
                                            <View
                                                className={styles.info}
                                                onClick={() => {
                                                    myOrderDetailStore.setOrderDetail(order);
                                                    // 跳转到订单详情页
                                                    Taro.navigateTo({
                                                        url: `/subPages/MyOrderDetail/MyOrderDetail`
                                                    })
                                                }}
                                            >
                                                <View className={styles.name}>{goods.productName || "--"}</View>
                                                <View className={styles.goodsCode}>编码: {goods.utStyleNum}</View>
                                                {
                                                    /^[\u4e00-\u9fa5]+$/.test(goods.color) &&
                                                    <View className={styles.goodsColor}>颜色: {goods.color}</View>
                                                }
                                                <View className={styles.spec}>
                                                    尺码: {goods.size}
                                                    <View className={styles.number}>×{goods.productNumber}</View>
                                                </View>
                                                <View className={styles.price}>¥{goods.productPrice}</View>
                                            </View>
                                        </View>
                                    ))}

                                    <View className={styles.footer}>
                                        {
                                            order.orderState === 'WAIT_PAY' &&
                                            <Button
                                                className={styles.cancel_btn}
                                                onClick={() => myOrderStore.cancelOrder(order.orderCodeMain)}
                                            >取消</Button>
                                        }
                                        {
                                            order.orderState === 'CLOSED' &&
                                            <Del
                                                className={styles.delete_btn}
                                                onClick={() => {
                                                    Taro.showModal({
                                                        title: '确认删除',
                                                        content: '确定要删除此订单吗？删除后将无法恢复。',
                                                        success: (res) => {
                                                            if (res.confirm) {
                                                                myOrderStore.deleteOrder(order.orderCodeMain);
                                                            }
                                                        }
                                                    });
                                                }}
                                            />
                                        }

                                        {/* 判断运单号是否以OFFLINE开头 */}
                                        {
                                            order.deliveryCode?.startsWith('OFFLINE') ? (
                                                order.orderState !== 'CLOSED' ? <span className={styles.offline} style={{ color: '#666', fontSize: '14px' }}>线下发货</span> : null
                                            ) : (
                                                order.deliveryCode &&
                                                order.orderState !== 'CLOSED' &&
                                                <Button
                                                    className={styles.ensure_btn}
                                                    type='primary'
                                                    onClick={async () => {
                                                        const deliveryInfo: Array<{ context: string; ftime: string; time: string }> =
                                                            await myOrderApi.queryDeliveryInfo(order.deliveryCode);
                                                        // 使用MobX store显示弹窗
                                                        logisticsStore.showLogisticsPopup(deliveryInfo);
                                                    }}
                                                >查询物流</Button>
                                            )
                                        }
                                        &nbsp;&nbsp;
                                        {
                                            order.orderState === 'DELIVERED' &&
                                            <Button
                                                className={styles.ensure_btn}
                                                type='primary'
                                                onClick={() => {
                                                    Taro.showModal({
                                                        title: '确认收货',
                                                        content: '确定要确认收货吗？',
                                                        success: (res) => {
                                                            if (res.confirm) {
                                                                myOrderStore.ensureOrder(order.orderCodeMain);
                                                            }
                                                        }
                                                    });
                                                }}
                                            >确认收货</Button>
                                        }

                                        <Text className={styles.total}>
                                            共{order.childrenList.length}件商品 合计:<Text className={styles.amount}> ¥{order.actualPrice}</Text>
                                        </Text>
                                    </View>
                                </View>
                            )
                        })
                    }
                </MyScrollView>
            }
        </PageLayer>
    )
}






